const EncryptHelper = require('../lib/EncryptHelper')
const HomeAssistant = require('../lib/HomeAssistant')

module.exports = function (RED) {
    RED.nodes.registerType('ha-wechat', function (config) {
        RED.nodes.createNode(this, config);
        const node = this
        const { hassUrl, hassToken, topic, uid } = config
        const server = RED.nodes.getNode(config.server);
        if (server && hassUrl && hassToken && topic && uid) {
            server.register(this)
            const ha = new HomeAssistant({ hassUrl, hassToken })
            // 消息临时存储
            const list = []
            server.subscribe(topic.replace('/wechat', ''), { qos: 0 }, async function (mtopic, mpayload, mpacket) {
                try {
                    const helper = new EncryptHelper(uid, 'ha-wechat')
                    const message = helper.Decrypt(mpayload.toString())
                    // 解析消息
                    const { id, time, text } = JSON.parse(message)

                    // 判断是否过期
                    now = parseInt(Date.now() / 1000)

                    if (now - 5 > time) {
                        return node.status({ fill: "red", shape: "ring", text: "消息过期，拒绝执行" });
                    }

                    // 判断是否重复
                    if (list.findIndex(ele => ele.id === id) >= 0) {
                        return node.status({ fill: "red", shape: "ring", text: "消息重复，拒绝执行" });
                    } else {
                        // 10秒后删除临时标识
                        list.filter(ele => now - 10 > ele.time).forEach(ele => {
                            const index = list.findIndex(item => item.id === ele.id)
                            list.splice(index, 1)
                        })
                    }
                    // console.log('消息队列', list.length)
                    // 加入消息队列
                    list.push({ id, time })

                    node.send({ payload: text })

                    // 文本识别
                    const res = await ha.postApi('conversation/process', { text })
                    const { plain } = res.speech
                    // console.log(plain)

                    // 发送消息
                    server.client.publish(`shaonianzhentan/homeassistant/${id}`, helper.Encrypt(JSON.stringify(plain)))

                    node.status({ fill: "green", shape: "ring", text: "消息回复成功" });
                } catch (ex) {
                    console.log(ex)
                    node.status({ fill: "red", shape: "ring", text: JSON.stringify(ex) });
                }
            })
        } else {
            this.status({ fill: "red", shape: "ring", text: "未配置相关信息" });
        }
    })
}